package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import saleMarket.domain.Customer;
import saleMarket.domain.FreightCargo;
import saleMarket.domain.InventoryGoods;
import saleMarket.domain.Order;
import saleMarket.service.*;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/shopping.ctl")
public class ShoppingController extends HttpServlet {
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String inventoryGoodsToUpdate_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为要修改的InventoryGoods对象（有id的完整对象）
        InventoryGoods inventoryGoodsToUpdate = JSON.parseObject
                (inventoryGoodsToUpdate_jsonStr, InventoryGoods.class);
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            inventoryGoodsToUpdate.setStock(InventoryGoodsService.getInstance().
                    find(inventoryGoodsToUpdate.getId()).getStock()-inventoryGoodsToUpdate.getStock());
            if (InventoryGoodsService.getInstance().buy(inventoryGoodsToUpdate)) {
                System.out.println(inventoryGoodsToUpdate);
               FreightCargo freightCargo =new FreightCargo("未发货",inventoryGoodsToUpdate,
                       LogisticsService.getInstance().find(1));
                Integer id =FreightCargoService.getInstance().add(freightCargo);
                freightCargo.setId(id);
                Order orderToAdd = new Order("已付款",inventoryGoodsToUpdate.getShop().getShopowner(),
                        CustomerService.getInstance().find(1),
                        freightCargo);
                if(OrderService.getInstance().add(orderToAdd)) {
                    respMessage_jsonObj.put("message", "购买成功,可查看订单物流信息！");
                }else {
                    respMessage_jsonObj.put("message","订单增加失败");
                }

            } else {
                respMessage_jsonObj.put("message", "库存不足，购买失败");
            }

        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
        } catch (Exception e) {
            respMessage_jsonObj.put("message", e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

}
